package org.opsli.modulars.mini;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.opsli.api.base.result.ResultWrapper;
import org.opsli.api.web.shop.shopconfig.ShopConfigRestApi;
import org.opsli.api.web.shop.userorder.ShopUserOrderRestApi;
import org.opsli.api.web.system.user.UserApi;
import org.opsli.api.wrapper.shop.userorder.ShopUserOrderModel;
import org.opsli.api.wrapper.system.user.UserModel;
import org.opsli.common.exception.ServiceException;
import org.opsli.core.utils.UserUtil;
import org.opsli.modulars.weixinPay.Confiig.WxPayConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Api(tags = ShopConfigRestApi.TITLEWECHATMINI)
@Slf4j
@RestController
@RequestMapping("/weMini/orderUser")
public class ShopUserRestController {

    @Autowired
    ShopUserOrderRestApi shopUserOrderRestApi;

    @Autowired
    UserApi userApi;
    @Resource
    WxPayConfiguration wxPayConfiguration;

    @Transactional
    @PostMapping("/yuyue")
    @ApiOperation(value = "获得单条店铺配置", notes = "获得单条店铺配置 - ID")
    public ResultWrapper<?> yuyue(@RequestBody ShopUserOrderModel model) {
        model.setStatus(1);
        yuyue2(model);

//        return model;
        // 如果系统内部调用 则直接查数据库
        return ResultWrapper.OK("预约成功");
    }


    @Transactional
    @ApiOperation(value = "获得单条店铺配置", notes = "获得单条店铺配置 - ID")
    public ShopUserOrderModel yuyue2(@RequestBody ShopUserOrderModel model) {
        UserModel user = userApi.getById(UserUtil.getUser().getId()).getData();
        QueryWrapper q = new QueryWrapper();
        if (user.getVipNumber() < 1 || DateUtil.date().isAfter(user.getVipendDate())) {
            throw new ServiceException(500, "该场地仅会员和次数大于0可预约");
        }
        q.eq("date", model.getDate());
        q.eq("title", model.getTitle());
        q.eq("status", 1);
        if (shopUserOrderRestApi.list(q).size() > 1) {
            throw new ServiceException(500, "该场次已经被他人预定");
        }

        model.setOrgIds(model.getOrgIds());
        model.setUid(UserUtil.getUser().getId());
        model = shopUserOrderRestApi.insert(model).getData();

        if (model.getStatus() == 1) {
            user.setVipNumber(user.getVipNumber() - 1);
            user.setPassword("Bb123456.");
            userApi.update(user);
            UserUtil.refreshUser(UserUtil.getUser());
        }

//    userApi.updateVipNumber(user.getId(),user.getVipNumber());
//        return model;
        // 如果系统内部调用 则直接查数据库
        return model;
    }

    @PostMapping("/getOrderList")
    @ApiOperation(value = "获得单条店铺配置", notes = "获得单条店铺配置 - ID")
    public ResultWrapper<?> getOrderList() {
        QueryWrapper q = new QueryWrapper();
        // 如果系统内部调用 则直接查数据库
        return ResultWrapper.getSuccessResultWrapper(shopUserOrderRestApi.list(q));
    }

    @PostMapping("/payDingjin")
    @ApiOperation(value = "获得单条店铺配置", notes = "获得单条店铺配置 - ID")
    public ResultWrapper<?> payDingjin(@RequestBody ShopUserOrderModel model) {
        model.setStatus(0);
        model.setDingjin(model.getDingjin().multiply(new BigDecimal(100)));
        model.setDingjinStatus(0);
        model = yuyue2(model);
        WxPayUnifiedOrderRequest wr = new WxPayUnifiedOrderRequest();
        wr.setBody("场地定金");
        wr.setOutTradeNo(model.getId());
        wr.setTotalFee(model.getDingjin().intValue());
        wr.setSpbillCreateIp("127.0.0.1");

        wr.setTradeType("JSAPI");
        wr.setOpenid(UserUtil.getUser().getOpenid());
        Object o;
        try {
            o = wxPayConfiguration.getwxService().createOrder(wr);
        } catch (WxPayException e) {
            throw new RuntimeException(e);
        }
        // 如果系统内部调用 则直接查数据库
        return ResultWrapper.getSuccessResultWrapper(o);
    }


    @ApiOperation(value = "退款")
    @GetMapping("/refund")
    public ResultWrapper<?> refund(String id) throws WxPayException {
        WxPayRefundRequest request = new WxPayRefundRequest();
        ShopUserOrderModel model = shopUserOrderRestApi.getById(id).getData();
        request.setOutTradeNo(model.getId());
        request.setOutRefundNo(model.getId());
        request.setTotalFee(model.getDingjin().intValue());
        request.setRefundFee(model.getDingjin().intValue());
        request.setOpUserId("000");
        WxPayRefundResult refundResult = wxPayConfiguration.getwxService().refund(request);
        if (refundResult.getReturnCode().equals("SUCCESS")) {
            model.setIzManual(true);
            model.setCreateBy(model.getUid());
            model.setUpdateBy(model.getUid());
            model.setDingjinStatus(2);
//            if (model.getStatus() == 1) {
//                model.setStatus(3);
//            } else {
//
//            }

            shopUserOrderRestApi.update(model);
//            if (model.getStatus() == 1 || model.getStatus() == 2) {
//                userApi.updateVipNumber(model.getUid(), 1);
//            }

            return ResultWrapper.OK("退款成功");
        }
        return ResultWrapper.getCustomResultWrapper(500, refundResult.getErrCodeDes());
    }


    @Transactional
    @GetMapping("/orderCancel")
    @ApiOperation(value = "获得单条店铺配置", notes = "获得单条店铺配置 - ID")
    public ResultWrapper<?> orderCancel(String id) {
        ShopUserOrderModel shopUserOrderModel = new ShopUserOrderModel();
        shopUserOrderModel.setId(id);
        shopUserOrderModel.setIzApi(true);
        shopUserOrderModel = shopUserOrderRestApi.get(shopUserOrderModel).getData();

        // 如果系统内部调用 则直接查数据库
        UserModel user = userApi.getById(shopUserOrderModel.getUid()).getData();
        QueryWrapper q = new QueryWrapper();


        q.eq("id", id);
        q.eq("status", 1);
        if (shopUserOrderRestApi.list(q).size() != 1) {
            return ResultWrapper.getCustomResultWrapper(500, "该场次已无法取消");
        }
        shopUserOrderModel.setStatus(3);
        shopUserOrderRestApi.update(shopUserOrderModel);
        user.setVipNumber(user.getVipNumber() + 1);
        user.setPassword("Bb123456.");
        userApi.update(user);
        UserUtil.refreshUser(user);
        // 如果系统内部调用 则直接查数据库
        return ResultWrapper.OK("取消成功");

    }

    @GetMapping("/orderConfirm")
    @ApiOperation(value = "获得单条店铺配置", notes = "获得单条店铺配置 - ID")
    public ResultWrapper<?> orderConfirm(String id) {

        ShopUserOrderModel model = new ShopUserOrderModel();
        model.setId(id);
        model.setIzApi(true);
        model = shopUserOrderRestApi.get(model).getData();

        if (model.getStatus() != 1) {
            return ResultWrapper.getCustomResultWrapper(500, "该场次已无法确认");
        }
        model.setStatus(2);
//        model.setUid(UserUtil.getUser().getId());
        shopUserOrderRestApi.update(model);
        UserUtil.refreshUser(userApi.getById(model.getUid()).getData());
        // 如果系统内部调用 则直接查数据库
        return ResultWrapper.getSuccessResultWrapper();
    }
}
